package com.test.controller.filterandsearch;

import com.test.bean.BaseConnectionInfo;
import com.test.bean.DataBaseInfo;
import com.test.service.IDataBaseService;
import com.test.service.IFilterAndSearchService;
import com.test.util.ConvertUtil;
import com.test.util.CreateBaseConnectionInfo;
import com.test.util.datasource.DBIdentifier;
import com.test.util.datasource.ProjectDBMgr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description
 * @auther Lelouch
 * @create 2018-12-26  15:46
 */
@RestController
@RequestMapping("/databasesearch")
@SuppressWarnings("all")
public class DataBaseController {
    private static Logger logger = LoggerFactory.getLogger(DataBaseController.class);

    @Autowired
    private IDataBaseService dataBaseService;
    @Autowired
    private IFilterAndSearchService filterAndSearchService;

    private Map<String, Map> cacheMap = new LinkedHashMap<>();

    @RequestMapping(value = "/queryAllDataBase", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    @ResponseBody
    public Object queryAllDataBase(HttpServletRequest request) {
        String nodeId = request.getParameter("id");
        List<Map> treeList = new ArrayList<>();
        if(null == nodeId || "#".equals(nodeId) || "".equals(nodeId)) {
            String schemaCode = "noInfo";
            DBIdentifier.setProjectCode(schemaCode);//后面设置为数据表那条信息的id
            List<DataBaseInfo> dataBaseInfoList = dataBaseService.queryAllDataBase(new HashMap());
            if(null != dataBaseInfoList && 0 < dataBaseInfoList.size()) {
                for(DataBaseInfo baseInfo : dataBaseInfoList) {
                    Map infoMap = new HashMap();
                    infoMap.put("id", baseInfo.getDataBaseId());
                    infoMap.put("text", baseInfo.getName());
                    infoMap.put("children", true);
                    treeList.add(infoMap);
                    infoMap.put("database", baseInfo);
                    cacheMap.put(baseInfo.getDataBaseId() + "", infoMap);
                }
            }
        }else {
            Map dataBaseMap = cacheMap.get(nodeId);
            if(null != dataBaseMap && !dataBaseMap.isEmpty()) {
                DataBaseInfo dataBaseInfo = (DataBaseInfo) dataBaseMap.get("database");
                //根据数据库连接信息查询到对应的所有表信息放到dataBaesMap的children中
                if(null != dataBaseInfo) {
                    //设置数据库连接方式 driver url username password
                    DBIdentifier.setProjectCode(nodeId);//后面设置为数据表那条信息的id
                    BaseConnectionInfo connectionInfo = CreateBaseConnectionInfo.getConnectionInfo(dataBaseInfo);
                    if(null != connectionInfo) {
                        ProjectDBMgr.getInstance(nodeId, connectionInfo);
                        //查询所有数据库表
                        Map param = new HashMap();
                        param.put("schema", dataBaseInfo.getDataBaseName());
                        try{
                            List result = filterAndSearchService.getAllTableName(param);
                            if(null != result && 0 < result.size()) {
                                List<Map> childrenList = new ArrayList<>();
                                for(int i = 0; i< result.size(); i ++) {
                                    Map tableNameMap = (Map) result.get(i);
                                    String tableName = ConvertUtil.converToString(tableNameMap.get("table_name"));
                                    tableNameMap.put("id", tableName);
                                    tableNameMap.put("text", tableName);
                                    childrenList.add(tableNameMap);
                                    dataBaseMap.put("children", childrenList);
                                }
                            }
                        }catch (Exception e) {
                            logger.error("查询所有表信息失败", e);
                        }
                    }
                }
                cacheMap.put(nodeId, dataBaseMap);
            }
            for(Map valueMap : cacheMap.values()) {
                treeList.add(valueMap);
            }
        }
        return treeList;
    }
}
